﻿using Dapper;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 功能菜单表T_Menu通用操作类
    /// </summary>
    public class MenuServices:Menus
    {
        public Pager<List<MenuModel>> GetPageList(MenuQuery query)
        {
            Pager<List<MenuModel>> obj = new Pager<List<MenuModel>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            if (!string.IsNullOrEmpty(query.MenuName.ToString().Trim()))
            {
                strWhereSql += "and MenuName like @MenuName ";
                paramlist.Add("MenuName", "%"+query.MenuName+"%");
            }
            if (!string.IsNullOrEmpty(query.Status.ToString().Trim()))
            {
                strWhereSql += "and Status = @Status ";
                paramlist.Add("Status", query.Status);
            }
            if (!string.IsNullOrEmpty(query.ParentId.ToString().Trim()))
            {
                strWhereSql += "and ParentId = @ParentId ";
                paramlist.Add("ParentId", query.ParentId);
            }
            string strFromSql = "from dbo.T_Menu where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = " order by Sort asc ";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MenuModel>(strSql,paramlist).ToList();
                    foreach (var item in obj.rows)
                    {
                        item.StatusName = DataDict.Instance["StatusList"][item.Status];
                        item.ParentName = string.IsNullOrEmpty(item.ParentId) ? "" : GetModel(item.ParentId).model.MenuName;
                    }
                    obj.total = dbCon.Query<int>(strTotal,paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取功能菜单表T_Menu分页列表失败", ex);
                return obj;
            }
        }


        public ResResult<List<MenuTree>> getUserMenu(string account, string userId)
        {
            ResResult<List<MenuTree>> obj = new ResResult<List<MenuTree>>();
            if (account == "admin")
            {
                obj.model = GetMenuTree("admin", userId, "");
                obj.status = DefaultKey.SuccessResult;
                obj.message = "获取admin菜单成功";
            }
            else
            {
                obj.model = GetMenuTree(account, userId, ""); ;
                obj.status = DefaultKey.SuccessResult;
                obj.message = "获取用户菜单成功";
            }
            return obj;
        }

        public List<MenuTree> GetMenuTree(string Account, string UserId, string MenuId)
        {
            List<MenuTree> listArea = new List<MenuTree>();
            MenuRoleServices Services = new MenuRoleServices();
            string strSql = @"select * from [dbo].[T_Menu] where ParentId=@MenuId order by Sort asc ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    List<MenuEntity> tempList = dbCon.Query<MenuEntity>(strSql, new { MenuId = MenuId }).ToList();
                    foreach (var item in tempList)
                    {
                        if (Account.Equals("admin"))
                        {
                            MenuTree model = new MenuTree();
                            model.Id = item.Id;
                            model.title = item.MenuName;
                            model.ParentId = MenuId;
                            model.icon = item.MenuIcon;
                            model.url = item.MenuUrl;
                            var childrenList = GetMenuTree(Account, UserId, model.Id);
                            model.expand = childrenList.Count == 0 ? false : true;
                            model.children = childrenList.Count == 0 ? new List<MenuTree>() : childrenList;
                            listArea.Add(model);
                        }
                        else
                        {
                            if (CheckUserMenu(UserId, item.Id))
                            {
                                MenuTree model = new MenuTree();
                                model.Id = item.Id;
                                model.title = item.MenuName;
                                model.ParentId = MenuId;
                                model.icon = item.MenuIcon;
                                model.url = item.MenuUrl;
                                var childrenList = GetMenuTree(Account, UserId, model.Id);
                                model.expand = childrenList.Count == 0 ? false : true;
                                model.children = childrenList.Count == 0 ? new List<MenuTree>() : childrenList;
                                listArea.Add(model);
                            }
                        }

                    }
                    return listArea;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取菜单树失败", ex);
                return listArea;
            }
        }


        public bool CheckUserMenu(string UserId, string MenuId)
        {
            string strSql = "select count(1) from dbo.T_Menu t1 ";
            strSql += "inner join dbo.T_MenuRole t2 on t1.Id=t2.MenuId ";
            strSql += "inner join dbo.T_Role t3 on t3.Id=t2.RoleId ";
            strSql += "inner join dbo.T_UserRole t4 on t4.RoleId=t3.Id ";
            strSql += "where t4.UserId=@UserId and t1.Id=@MenuId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (dbCon.Query<int>(strSql, new { UserId = UserId, MenuId = MenuId }).FirstOrDefault() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取功能菜单表T_Menu分页列表失败", ex);
                return false;
            }
        }

        /// <summary>
        /// 获取父级菜单
        /// </summary>
        /// <returns></returns>
        public ResResult<List<SortMenuModel>> GetParents()
        {
            ResResult<List<SortMenuModel>> obj = new ResResult<List<SortMenuModel>>();
            string strSql = "select MenuName,Id from dbo.T_Menu where ParentId = ''";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.model = dbCon.Query<SortMenuModel>(strSql).ToList();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取数据集成功";
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
            }
            return obj;
        }
    }
}